package ca.ubc.icapture.genapha.actions;

import ca.ubc.icapture.genapha.forms.AnalysisJobForm;
import ca.ubc.icapture.genapha.rmi.SnpInteractionJob;
import ca.ubc.icapture.genapha.forms.GeneGeneInteractionForm;
import ca.ubc.icapture.genapha.rmi.RemoteAnalysisInterface;
import icapture.AppProperties;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.Action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 * User: btripp
 * Date: Sep 13, 2006
 * Time: 9:39:08 AM
 * To change this template use File | Settings | File Templates.
 */
public class GeneGeneInteractionAction extends Action
{

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    {
        GeneGeneInteractionForm geneGeneForm = (GeneGeneInteractionForm) form;

        //perform analysis
        //make combined files

        // Create the form for the next page
        AnalysisJobForm ajf = new AnalysisJobForm();
        request.setAttribute("analysisJobForm", ajf);

        // Create a job
        SnpInteractionJob job = new SnpInteractionJob();
        job.setConditioningSnps(geneGeneForm.getConditioningSnps());
        job.setSelectedPhenotype(geneGeneForm.getSelectedPhenotype());
        job.setSelectedSnps(geneGeneForm.getSelectedSnps());
        job.setCohortIds(new String[] {"6", "7", "8"}); // NHL, Hapmap-CEU, Hapmap-JPT+CHB

        // Queue the job
        String id = null;
        try
        {
            Registry registry = LocateRegistry.getRegistry(AppProperties.get("analysisServer"));
            RemoteAnalysisInterface stub = (RemoteAnalysisInterface) registry.lookup("NHLAnalysisJob");
            id = stub.startNewJob(job);

            System.out.println("response: " + id);
        }
        catch (Exception e)
        {
            ajf.setLink("There was an error setting up the analysis. Please try again later.");
            // TODO: email me that a job failed
            System.err.println("Client exception: " + e.toString());
            e.printStackTrace();
        }

        // If job has been queued successfully, set up analysis job form
        if (id != null)
        {
            ajf.setAnalysisID(id);

            String link = "http://" + request.getServerName();
            if (request.getServerPort() != 80)
            {
                link = link + ":" + request.getServerPort();
            }
            link = link + request.getContextPath() + "/analysisResults.do?jobID=" + id;
            ajf.setLink(link);
        }

        return mapping.findForward("display");
    }
}
